package com.qyhl.party.party.study;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.gyf.immersionbar.ImmersionBar;
import com.qyhl.party.R;
import com.qyhl.party.R2;
import com.qyhl.party.party.PartyHomeActivity;
import com.qyhl.webtv.basiclib.base.BaseFragment;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.basiclib.utils.dialog.OtherDialog;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.act.Catalog;
import com.qyhl.webtv.commonlib.entity.news.NewsBean;
import com.qyhl.webtv.commonlib.entity.news.PartyBuildConfigBean;
import com.qyhl.webtv.commonlib.utils.action.ActionConstant;
import com.qyhl.webtv.commonlib.utils.action.ActionLogUtils;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.weavey.loading.lib.LoadingLayout;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;
import com.zhy.adapter.recyclerview.wrapper.HeaderAndFooterWrapper;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;
import butterknife.OnClick;

public class PartyStudyFragment extends BaseFragment implements PartyStudyContract.PartyStudyView {
    @BindView(R2.id.score)
    TextView score;
    @BindView(R2.id.recycler_view)
    RecyclerView recyclerView;
    @BindView(R2.id.refresh)
    SmartRefreshLayout refresh;
    @BindView(R2.id.load_mask)
    LoadingLayout loadMask;

    private String token;

    private PartyStudyPresenter mPresenter;

    private CommonAdapter<PartyBuildConfigBean> commonAdapter;

    private HeaderAndFooterWrapper<PartyBuildConfigBean> headerAndFooterWrapper;

    private List<PartyBuildConfigBean> mDataList = new ArrayList<>();

    public void setToken(String token) {
        this.token = token;
    }

    private int integral;

    public void setIntegral(int integral) {
        this.integral = integral;
    }

    public static PartyStudyFragment newInstance(String token, int integral) {
        PartyStudyFragment fragment = new PartyStudyFragment();
        fragment.setToken(token);
        fragment.setIntegral(integral);
        return fragment;
    }

    @SuppressLint("InflateParams")
    @Override
    protected View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.party_fragment_study, null);
    }

    @Override
    protected void onFirstVisible() {

    }

    @Override
    protected void onVisible() {

    }

    @Override
    protected void onHide() {

    }


    @Override
    public void initImmersionBar() {
        ImmersionBar.with(this)
                .statusBarDarkFont(false)
                .titleBar(R.id.title_layout)
                .init();
    }

    @SuppressLint("SetTextI18n")
    @Override
    protected void create() {
        loadMask.setStatus(LoadingLayout.Loading);
        mPresenter = new PartyStudyPresenter(this);

        refresh.setRefreshHeader(new MaterialHeader(getContext()));
        refresh.setRefreshFooter(new ClassicsFooter(getContext()));
        refresh.setEnableLoadMore(false);

        score.setText(integral + "");

        View headView = LayoutInflater.from(getContext()).inflate(R.layout.party_header_study, null);

        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        DividerItemDecoration divider = new DividerItemDecoration(Objects.requireNonNull(getContext()), DividerItemDecoration.VERTICAL);
        divider.setDrawable(Objects.requireNonNull(ContextCompat.getDrawable(getContext(), R.drawable.party_study_item_divider)));
        recyclerView.addItemDecoration(divider);
        //判断评论数是否大于最少浏览数
        commonAdapter = new CommonAdapter<PartyBuildConfigBean>(getContext(), R.layout.party_item_study, mDataList) {
            @Override
            protected void convert(ViewHolder holder, PartyBuildConfigBean bean, int position) {
                holder.setText(R.id.title, bean.getCatalogName());

                ImageView cover = holder.getView(R.id.cover);
                Glide.with(PartyStudyFragment.this)
                        .load(bean.getInfo().getLogo())
                        .apply(new RequestOptions().placeholder(R.drawable.cover_large_default).error(R.drawable.cover_large_default))
                        .into(cover);

                holder.setOnClickListener(R.id.all_btn, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (bean.getHomeStyle() == 0) {
                            ARouter.getInstance()
                                    .build(ARouterPathConstant.PARTY_SUBJECT_SINGLE)
                                    .withString("InnerCode", bean.getCatalogId() + "")
                                    .withString("title", bean.getCatalogName())
                                    .withString("logo", bean.getNewsList().get(0).getLogo())
                                    .navigation();
                        } else {
                            ARouter.getInstance()
                                    .build(ARouterPathConstant.PARTY_SUBJECT)
                                    .withInt("style", bean.getChildStyle())
                                    .withString("title", bean.getCatalogName())
                                    .withString("logo", bean.getInfo().getLogo())
                                    .withInt("catalogId", bean.getCatalogId())
                                    .navigation();
                        }

                    }
                });


                if (bean.getHomeStyle() == 0) {
                    holder.setVisible(R.id.news_recycler, true);

                    RecyclerView newsRecycler = holder.getView(R.id.news_recycler);
                    newsRecycler.setLayoutManager(new LinearLayoutManager(getContext()));
                    DividerItemDecoration divider = new DividerItemDecoration(Objects.requireNonNull(getContext()), DividerItemDecoration.VERTICAL);
                    divider.setDrawable(Objects.requireNonNull(ContextCompat.getDrawable(getContext(), R.drawable.party_study_item_divider)));
                    newsRecycler.addItemDecoration(divider);
                    CommonAdapter<NewsBean> newsAdapter = new CommonAdapter<NewsBean>(getContext(), R.layout.party_item_study_item, bean.getNewsList()) {
                        @Override
                        protected void convert(ViewHolder holder, NewsBean newsBean, int position) {
                            holder.setText(R.id.title, newsBean.getTitle());

                            if (StringUtils.isNotEmpty(newsBean.getSource())) {
                                holder.setVisible(R.id.origin, true);
                                holder.setText(R.id.origin, newsBean.getSource());
                            } else {
                                holder.setVisible(R.id.origin, false);
                            }

                            try {
                                int minPlay = Integer.parseInt(CommonUtils.getInstance().getMinPlay());
                                if (minPlay == 0) {
                                    holder.setVisible(R.id.scan_num, false);
                                } else {
                                    //判断评论数是否大于最少浏览数
                                    if (StringUtils.isEmpty(newsBean.getHitCount() + "")) {
                                        holder.setVisible(R.id.scan_num, false);
                                    } else if (Integer.parseInt(newsBean.getHitCount()) >=
                                            minPlay) {
                                        holder.setText(R.id.scan_num, StringUtils.transformNum(newsBean.getHitCount()) + "阅");
                                        holder.setVisible(R.id.scan_num, true);
                                    } else {
                                        holder.setVisible(R.id.scan_num, false);
                                    }
                                }

                            } catch (Exception e) {
                                holder.setVisible(R.id.scan_num, false);
                            }
                        }
                    };
                    newsRecycler.setAdapter(newsAdapter);

                    newsAdapter.setOnItemClickListener(new OnItemClickListener() {
                        @Override
                        public void onItemClick(View view, RecyclerView.ViewHolder viewHolder, int i) {
                            NewsBean newsBean = bean.getNewsList().get(i);
                            switch (newsBean.getType()) {
                                case "1"://普通新闻
                                {
                                    Bundle bundle = new Bundle();
                                    bundle.putString("id", newsBean.getID());
                                    RouterManager.router(ARouterPathConstant.NORMAL_NEWS_ACTIVITY, bundle);
                                    ActionLogUtils.getInstance().onEvent(ActionConstant.PARTY_STUDY_NEWS);
                                }
                                break;
                                case "2"://图片新闻
                                {
                                    Bundle bundle = new Bundle();
                                    bundle.putString("id", newsBean.getID());
                                    bundle.putString("section", newsBean.getCatalogID());
                                    RouterManager.router(ARouterPathConstant.PICTURE_NEWS_ACTIVITY, bundle);
                                    ActionLogUtils.getInstance().onEvent(ActionConstant.PARTY_STUDY_NEWS);
                                }

                                break;
                                case "3"://直播
                                {
                                    Bundle bundle = new Bundle();
                                    bundle.putString("newsId", newsBean.getID());
                                    bundle.putString("liveType", newsBean.getLivetype());
                                    RouterManager.router(ARouterPathConstant.LIVE_NORMAL_ACTIVITY, bundle);
                                    ActionLogUtils.getInstance().onEvent(ActionConstant.PARTY_STUDY_LIVE);
                                }
                                break;
                                case "4"://标题新闻
                                {
                                    Bundle bundle = new Bundle();
                                    bundle.putString("id", newsBean.getID());
                                    bundle.putString("title", newsBean.getTitle());
                                    bundle.putString("url", newsBean.getRedirectURL());
                                    RouterManager.router(ARouterPathConstant.ADV, bundle);
                                    ActionLogUtils.getInstance().onEvent(ActionConstant.PARTY_STUDY_NEWS);
                                }
                                break;
                                case "5"://视频新闻
                                {
                                    Bundle bundle = new Bundle();
                                    bundle.putString("id", newsBean.getID());
                                    RouterManager.router(ARouterPathConstant.VIDEO_NEWS_ACTIVITY, bundle);
                                    ActionLogUtils.getInstance().onEvent(ActionConstant.PARTY_STUDY_LIVE);
                                }
                                break;
                                case "8"://互动直播
                                    break;
                                case "101"://抓取新闻
                                {
                                    Bundle bundle = new Bundle();
                                    bundle.putString("id", newsBean.getID());
                                    RouterManager.router(ARouterPathConstant.NEWS_CATCH, bundle);
                                    ActionLogUtils.getInstance().onEvent(ActionConstant.PARTY_STUDY_NEWS);
                                }
                                break;
                                default:
                                    break;

                            }
                        }

                        @Override
                        public boolean onItemLongClick(View view, RecyclerView.ViewHolder viewHolder, int i) {
                            return false;
                        }
                    });
                } else {
                    holder.setVisible(R.id.news_recycler, false);
                }
            }
        };

        headerAndFooterWrapper = new HeaderAndFooterWrapper<>(commonAdapter);
        headerAndFooterWrapper.addHeaderView(headView);

        recyclerView.setAdapter(headerAndFooterWrapper);

        mPresenter.getConfig();
    }

    @Override
    protected void setListener() {
        loadMask.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                loadMask.setReloadButtonText("加载中...");
                mPresenter.getConfig();
            }
        });

        refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                mPresenter.getConfig();
            }
        });

        commonAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder viewHolder, int i) {
                PartyBuildConfigBean bean = mDataList.get(i - 1);
                if (bean.getHomeStyle() == 0) {
                    ARouter.getInstance()
                            .build(ARouterPathConstant.PARTY_SUBJECT_SINGLE)
                            .withString("InnerCode", bean.getCatalogId() + "")
                            .withString("title", bean.getCatalogName())
                            .withString("logo", bean.getInfo().getLogo())
                            .navigation();
                } else {
                    ARouter.getInstance()
                            .build(ARouterPathConstant.PARTY_SUBJECT)
                            .withInt("style", bean.getChildStyle())
                            .withString("title", bean.getCatalogName())
                            .withString("logo", bean.getInfo().getLogo())
                            .withInt("catalogId", bean.getCatalogId())
                            .navigation();
                }
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder viewHolder, int i) {
                return false;
            }
        });


    }


    @Override
    public void setConfig(List<PartyBuildConfigBean> beanList) {
        mDataList.clear();
        mDataList.addAll(beanList);

        for (int i = 0; i < mDataList.size(); i++) {
            mPresenter.getConfigInfo(mDataList.get(i).getCatalogId() + "", i);
            if (mDataList.get(i).getHomeStyle() == 0) {
                mPresenter.getList(mDataList.get(i).getCatalogId() + "", i);
            }

        }
    }

    @Override
    public void setInfo(Catalog bean, int position) {
        mDataList.get(position).setInfo(bean);
        boolean needRefresh = true;
        for (int i = 0; i < mDataList.size(); i++) {
            if (mDataList.get(i).getHomeStyle() == 0) {
                if (mDataList.get(i).getNewsList() == null) {
                    needRefresh = false;
                }
            }

            if (mDataList.get(i).getInfo() == null) {
                needRefresh = false;
            }
        }


        if (needRefresh) {
            loadMask.setReloadButtonText("点击重试~");
            loadMask.setStatus(LoadingLayout.Success);
            refresh.finishRefresh();
            headerAndFooterWrapper.notifyDataSetChanged();
        }
    }

    @Override
    public void setList(List<NewsBean> beanList, int position) {
        List<NewsBean> indexList = new ArrayList<>();
        for (int i = 0; i < (Math.min(beanList.size(), 2)); i++) {
            indexList.add(beanList.get(i));
        }
        mDataList.get(position).setNewsList(indexList);
        boolean needRefresh = true;
        for (int i = 0; i < mDataList.size(); i++) {
            if (mDataList.get(i).getHomeStyle() == 0) {
                if (mDataList.get(i).getNewsList() == null) {
                    needRefresh = false;
                }
            }

            if (mDataList.get(i).getHomeStyle() == 1) {
                if (mDataList.get(i).getInfo() == null) {
                    needRefresh = false;
                }
            }
        }

        if (needRefresh) {
            loadMask.setReloadButtonText("点击重试~");
            loadMask.setStatus(LoadingLayout.Success);
            refresh.finishRefresh();
            headerAndFooterWrapper.notifyDataSetChanged();
        }
    }

    @Override
    public void setError(String msg) {
        loadMask.setReloadButtonText("点击重试~");
        loadMask.setStatus(LoadingLayout.Error);
        loadMask.setErrorText(msg);
        refresh.finishRefresh();
    }

    @OnClick({R2.id.center, R2.id.score_rule, R2.id.search_bar, R2.id.back_btn})
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.center) {
            ARouter.getInstance()
                    .build(ARouterPathConstant.PARTY_USER_CENTER)
                    .withString("token", token)
                    .navigation();
        } else if (id == R.id.score_rule) {
            new OtherDialog.Builder(getContext())
                    .setContentView(R.layout.party_dialog_score_rule)
                    .setGravity(Gravity.CENTER)
                    .setWidth(0.8f)
                    .setDismissButton(R.id.close_btn)
                    .show();
        } else if (id == R.id.search_bar) {
            RouterManager.router(ARouterPathConstant.SEARCH);
        } else if (id == R.id.back_btn) {
            if (getActivity() instanceof PartyHomeActivity) {
                ((PartyHomeActivity) getActivity()).doFinish();
            }
        }
    }
}
